package com.jwt.interceptor;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jwt.util.JwtUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录拦截器
 */
@Configuration
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("utf-8");
        //获取token中存储的登录用户的信息
        String requestHeader = request.getHeader("Authorization");
        System.out.println("拦截器获取请求头传递的token="+requestHeader);
        String token = request.getParameter("token");
        System.out.println("拦截器获取的token="+token);
        if("".equals(requestHeader)  &&  "".equals(token) ){
            //判断是否是Ajax请求  获取到请求头中的Ajax参数
            String XRequested =request.getHeader("X-Requested-With");
            //Ajax请求中带有的参数
            String ajaxReq = "XMLHttpRequest";
            if(ajaxReq.equals(XRequested)) {
                Map<String, Object> map = new HashMap<>(1);
                map.put("result", "IsAdminAjax");
                ObjectMapper mapper = new ObjectMapper();
                String data = mapper.writeValueAsString(map);
                response.getWriter().write(data);
                return false;
            } else {
                System.out.println("拦截请求");
                System.out.println("请求地址为：" + request.getRequestURI());
                response.sendRedirect(request.getContextPath()+"/index");
            }
            return false;
        }else {
            DecodedJWT verify = JwtUtil.verify(token);
            if (verify == null){
                Map<String, Object> map = new HashMap<>(1);
                map.put("msg", "校验失败");
                ObjectMapper mapper = new ObjectMapper();
                String data = mapper.writeValueAsString(map);
                response.getWriter().write(data);
                return false;
            }
        }
        return true;
    }

}
